package com.ruoyi.business.util;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;

//同盾工具类
/**
 * aes加解密
 */
public class TDAESUtil {
    private static final Logger logger = LoggerFactory.getLogger(TDAESUtil.class);
    private static final String SECRET = "tongdun@lingxin1";

    // 加密
    public static String Encrypt(String sSrc, String sKey) throws BusinessException {
        if (sKey == null) {
            sKey = SECRET;
        }
        // 判断Key是否为16位
        if (sKey.length() != 16) {
            return "";
        }
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            return new Base64().encodeToString(encrypted);
        } catch (Exception e) {
            logger.error("AESUtil-Encrypt异常sSrc:{},sKey:{}", sSrc, sKey,e);
            throw new BusinessException(RspEnmu.TD_ASE_ENCRYPY_ERROR);
        }
    }

    // 解密
    public static String Decrypt(String sSrc, String sKey) throws BusinessException {
        try {
            // 判断Key是否正确
            if (sKey == null) {
                sKey = SECRET;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                return "";
            }
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = new Base64().decode(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception e) {
            logger.error("AESUtil-Decrypt异常sSrc:{},sKey:{}", sSrc, sKey,e);
            throw new BusinessException(RspEnmu.TD_ASE_DNCRYPY_ERROR);
        }
    }

}
